﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Windows.Markup;
using System.IO.IsolatedStorage;
using System.Text.RegularExpressions;

namespace Twatcher
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        Boolean isDuplicate = false;
        Boolean isChange = false;
        public List<String> headerSet = new List<String>();
        TwitterService.Trend selecttrend;

        private const string WhatTheTrendSearchQuery = "http://api.whatthetrend.com/api/v2/trends.json?api_key={efe1aac79e91358ab458d27ffcb70581fd458a19}";

        #region Loaded Event

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }

        }

        private void pitmHome_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            TwitterService.TwitterService.GetTrends(
               (items) => { trendList.ItemsSource = items; },
               (exception) => { MessageBox.Show(exception.Message); },
               null
               );
            homePop.Begin();
        }

        #endregion

        #region Home Event

        private void btnAddTag_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            isDuplicate = false;
            String searchName;
            if (tbTag.Text.Contains("#"))
            {
                searchName = Regex.Replace(tbTag.Text.ToString(), @"[#]", "");
            }
            else
            {
                searchName = tbTag.Text;
            }
            addNewPage(searchName, true, true);
            tbTag.Text = "";
        }

        private void trendList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            selecttrend = trendList.SelectedItem as TwitterService.Trend;
            String searchName;
            if (selecttrend.name.Contains("#"))
            {
                searchName = Regex.Replace(selecttrend.name.ToString(), @"[#]", "");
            }
            else
            {
                searchName = selecttrend.name.ToString();
            }
            addNewPage(searchName, true, true);
        }

        #endregion

        #region AppBar Event

        private void btnSaveTag_Click(object sender, System.EventArgs e)
        {
            PivotItem selectItem = myPivot.SelectedItem as PivotItem;
            if ((selectItem.Header.Equals("home")) | (selectItem.Header.Equals("about")))
            {
                    
            }
            else
            {
                this.headerSet.Add(selectItem.Header.ToString());
                MessageBox.Show("Saving "+ selectItem.Header.ToString());
            }
            isChange = true;
        }

        private void btnSetting_Click(object sender, System.EventArgs e)
        {
            PivotItem currItem = myPivot.SelectedItem as PivotItem;
            String searchName = Regex.Replace(currItem.Header.ToString(), @"[#]", "");
            ListBox twList = new ListBox();
            twList.ItemTemplate = this.CreateTagTweetTemplate();
            
            TwitterService.TwitterService.Search(
                (searchName),
                (items) => { twList.ItemsSource = items; },
                (exception) => { MessageBox.Show(exception.Message); },
                null
                );

            currItem.Content = twList;

        }

        private void btnDeleteTag_Click(object sender, System.EventArgs e)
        {
            PivotItem selectItem = myPivot.SelectedItem as PivotItem;
            if (MessageBox.Show("Really?", "Delete "+selectItem.Header.ToString() , MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                if ((selectItem.Header.Equals("home")) | (selectItem.Header.Equals("about")))
                {

                }
                else
                {
                    this.headerSet.Remove(selectItem.Header.ToString());
                }
                IsolatedStorageSettings s = IsolatedStorageSettings.ApplicationSettings;
                s.Remove("saveTrend");
                s.Add("saveTrend", headerSet);
                s.Save();
            }
        }

        private void btnLoad_Click(object sender, System.EventArgs e)
        {
            IsolatedStorageSettings s = IsolatedStorageSettings.ApplicationSettings;
            if (s.Contains("saveTrend"))
            {
                List<String> loadList = new List<String>();
                loadList = (List<String>)s["saveTrend"];
                String searchName = "";
                foreach (String item in loadList)
                {
                    if (!(headerSet.Contains(item)))
                    {
                        this.headerSet.Add(item);
                    }
                    searchName = Regex.Replace(item, @"[#]", "");
                    addNewPage(searchName, false, false);
                }
            }
            else
            {
                MessageBox.Show("There noting saved to load.");
            }
        }

        #endregion

        #region App Event

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (isChange)
            {
                IsolatedStorageSettings s = IsolatedStorageSettings.ApplicationSettings;
                s.Remove("saveTrend");
                s.Add("saveTrend", headerSet);
                s.Save();
            }
            if (MessageBox.Show("Really?", "Wanna Exit", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
            {
                e.Cancel = true;
            }
        }

        #endregion

        #region Homebrew Method

        private void addNewPage(String search, Boolean msg, Boolean navi)
        {
            int pivotIndex = 0;
            foreach (PivotItem item in myPivot.Items)
            {
                if (item.Header.Equals("#" + search))
                {
                    MessageBox.Show("You already add this Tag.");
                    isDuplicate = true;
                    break;
                }
            }
            if (!isDuplicate)
            {
                var pitem = new PivotItem(); //create pivotitem 
                pitem.Header = "#" + search;
                ListBox twList = new ListBox();
                twList.ItemTemplate = this.CreateTagTweetTemplate();

                TwitterService.TwitterService.Search(
                (search),
                (items) => { twList.ItemsSource = items; },
                (exception) => { MessageBox.Show(exception.Message); },
                null
                );

                pitem.Content = twList;//set pivotitem content
                myPivot.Items.Add(pitem);//Add pivotitem to your pivot
                if (msg)
                {
                    MessageBox.Show("Adding Complete.Feel free to browse it.");
                }
                if (navi)
                {
                    foreach (PivotItem item in myPivot.Items)
                    {
                        if (item.Header.Equals("#" + search))
                        {
                            myPivot.SelectedIndex = pivotIndex;
                            break;
                        }
                        pivotIndex++;
                    }
                }
            }
        }

        #endregion

        #region Template

        private DataTemplate CreateTagTweetTemplate()
        {
            string xaml =
                @"<DataTemplate
                   xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
                   xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
    		        <Grid Width='456' Height='120' Background='#4C000000'>
    			        <Grid.ColumnDefinitions>
    				        <ColumnDefinition Width='120'/>
    				        <ColumnDefinition/>
    			        </Grid.ColumnDefinitions>
    			        <Border BorderBrush='#7FFFFFFF' BorderThickness='1' Grid.ColumnSpan='2'/>
    			        <Image x:Name='twUsrImg' Margin='5' Stretch='UniformToFill' Source='{Binding profile_image_url}'/>
    			        <StackPanel Margin='2,0,1,0' Grid.Column='1'>
    				        <Grid Background='#7F000000' Margin='5' VerticalAlignment='Top' Height='18'>
    					        <Grid.ColumnDefinitions>
    						        <ColumnDefinition Width='0.683*'/>
    						        <ColumnDefinition Width='0.317*'/>
    					        </Grid.ColumnDefinitions>
                                <Border BorderBrush='#7FFFFFFF' BorderThickness='1' Grid.Column='0'/>
    					        <TextBlock x:Name='twUsrBox' TextWrapping='Wrap' FontSize='16' Margin='10,0,0,0' Text='{Binding from_user}' HorizontalAlignment='Left' VerticalAlignment='Center'/>
                                <Border BorderBrush='#7FFFFFFF' BorderThickness='1' Grid.Column='1'/>
    					        <TextBlock x:Name='twDateBox' TextWrapping='Wrap' FontSize='10' Text='{Binding created_at}' Margin='0' Grid.Column='1' VerticalAlignment='Center' HorizontalAlignment='Right'/>
    				        </Grid>
    				        <StackPanel Margin='5,0,5,5' Background='#7F000000' Height='85'>
    					        <TextBlock x:Name='twTweetsBox' TextWrapping='Wrap' FontSize='16' Margin='3,0,0,3' Text='{Binding text}' Height='93'/>
    				        </StackPanel>
    			        </StackPanel>
    		        </Grid>
    	        </DataTemplate>";
            DataTemplate dt = (DataTemplate)XamlReader.Load(xaml);
            return dt;
        }

        #endregion

    }
}